package com.company.servicename.config;

import com.company.servicename.entity.AstUser;
import com.company.servicename.util.JwtTokenUtil;
import com.company.servicename.util.ScrUser;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

/**
 * @author fangsong.zhang
 * @date 2019/9/24 10:16
 * Copyright zfs
 * 类说明: 授权服务
 */
@Service
public class AuthServiceImpl {

    private static final Logger log = Logger.getLogger(AuthServiceImpl.class);

    @Autowired
    private UserDetailServiceImpl userDetailServiceImpl;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private ScrUser scrUser;

    /**
     * 登录逻辑
     *
     * @param astUser 用户登录信息
     * @return token
     */
    public String login(AstUser astUser) {
        String username = astUser.getUsername();
        String password = astUser.getPassword();
        if (scrUser.getUsername().equals(username)) {
            // 内存验证
            if (!scrUser.getPassword().equals(password)) {
                log.error("认证不通过");
                return "";
            }
        } else {
            try {
                // todo 数据库验证
            } catch (Exception e) {
                e.printStackTrace();
                log.error("认证不通过");
                return "";
            }
        }
        userDetailServiceImpl.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
        Authentication upToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = userDetailServiceImpl.loadUserByUsername(username);
        return jwtTokenUtil.generateToken(userDetails);
    }
}
